package org.onionframework.persistence.model.support;

import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class DefaultXMLMapConverter implements XMLMapConverter {

	@Override
	public Map<String, Object> toMap(String value) {
		Map<String,Object> map = new HashMap<String,Object>();
		if(StringUtils.isBlank(value))
			value = "<Root></Root>";
		
		Document document;
		try {
			document = DocumentHelper.parseText(value);
		} catch (DocumentException e) {
			throw new RuntimeException(e);
		}
		List<Element> properties = (List<Element>) document.getRootElement().elements();

		for (Element node : properties)
			map.put(node.getName(), node.getText());
		
		return map;
	}

	@Override
	public String toString(Map<String, Object> map) {
		Document document = DocumentHelper.createDocument(DocumentHelper.createElement("Root"));
		
		for(Map.Entry<String, Object> entry : map.entrySet()){
			Element propElement = DocumentHelper.createElement(entry.getKey());
			propElement.setText(entry.getValue() == null ? null : entry.getValue().toString());
			document.getRootElement().add(propElement);
		}
		
		Writer writer = new StringWriter();
		try {
			String stringValue = null;
			document.write(writer);
			stringValue = writer.toString();
			return stringValue;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}finally{
			try{writer.close();}catch(Exception ex){}
		}
	}

}
